<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/11/18
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\NodeService;
use app\common\facade\Arr;
use app\common\facade\Help;
use library\Controller;
use think\Db;
use library\tools\Data;

/**
 *代理商管理
 * Class Businessagent
 * @package app\admin\controller
 * @author feraner<feraner@163.com>
 * @date 2019/11/18
 */
class Businessagent extends Controller
{


    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'system_agent_user';




    /**
     * 代理商列表
     * @auth true
     * @menu true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        $this->title = '代理商管理';
        $query = $this->_query($this->table)
            ->like('username,phone,mail')
            ->equal('status');
        $query->dateBetween('login_at,create_at')
            ->where(['is_deleted' => '0'])
            ->where(['pid' => '0'])
            ->order('id desc')
            ->page();
    }

    /**
     * 列表数据处理
     * @param array $data
     * @throws \Exception
     */
    protected function _index_page_filter(&$data)
    {

        foreach ($data as &$vo) {
            $vo['province'] =DB::name("Area")->where('area_id',$vo['provinces_id'])->value("area_name");
            $vo['city'] =DB::name("Area")->where('area_id',$vo['city_id'])->value("area_name");
        }


    }

    /**
     * 添加代理商
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 添加代理商表单处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function _add_form_filter(&$data)
    {

        if ($this->request->isPost()) {

            $post_data['provinces_id']=$data['provinces_id'];
            $post_data['city_id']=$data['city_id'];
            $post_data['pid']=0;
            $result=DB::name("system_agent_user")
                    ->where($post_data)
                    ->find();
            if (!empty($result)) $this->error('该城市已经存在 代理商[ '.$result['username']."]");
        }
       
        
    }

    /**
     * 编辑代理商
     * @auth true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function edit()
    {
        $this->applyCsrfToken();
        $this->_form($this->table, 'form');
    }

    /**
     * 修改代理商密码
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pass()
    {
        $this->applyCsrfToken();
        if ($this->request->isGet()) {
            $this->verify = false;
            $this->_form($this->table, 'pass');
        } else {
            $post = $this->request->post();
            if ($post['password'] !== $post['repassword']) {
                $this->error('两次输入的密码不一致！');
            }
            $result = NodeService::checkpwd($post['password']);
            if (empty($result['code'])) $this->error($result['msg']);
            if (Data::save($this->table, ['id' => $post['id'], 'password' => md5($post['password'])], 'id')) {
                $this->success('密码修改成功，下次请使用新密码登录！', '');
            } else {
                $this->error('密码修改失败，请稍候再试！');
            }
        }
    }

    /**
     * 表单数据处理
     * @param array $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _form_filter(&$data)
    {
        if ($this->request->isPost()) {
            if(empty($this->request->param('id'))){
                //处理省市区 
                $province = Help::ignoreAreaSuffix(Arr::get($data, 'province'));
                $city = Help::ignoreAreaSuffix(Arr::get($data, 'city'));
                $county = Help::ignoreAreaSuffix(Arr::get($data, 'county'));
                $provinceId = Db::name('area')->where('area_name', 'LIKE', '%' . $province . '%')->value('area_id') ?: 0;
                $cityId = Db::name('area')->where('area_name', 'LIKE', '%' . $city . '%')->value('area_id') ?: 0;
                $countyId = Db::name('area')->where('area_name', 'LIKE', '%' . $county . '%')->value('area_id') ?: 0;
                if (!$provinceId || !$cityId) {
                    $this->error("请选择所属地区");
                } else {
                    $data['provinces_id'] = $provinceId;
                    $data['city_id'] = $cityId;
                    $data['county_id'] = $countyId;
                    unset($data['province'], $data['city'], $data['county']);
                }
            }
            if(empty(Help::ignoreAreaSuffix(Arr::get($data, 'bind_agent_user_id')))||Help::ignoreAreaSuffix(Arr::get($data, 'bind_agent_user_id'))=='0'){
                 $this->error("请绑定用户ID");
            }

            // 刷新系统授权
            NodeService::applyUserAuth();
            // 用户权限处理
            $data['authorize'] = (isset($data['authorize']) && is_array($data['authorize'])) ? join(',', $data['authorize']) : '';
            // 用户账号重复检查
            if (isset($data['id'])) unset($data['username']);
            elseif (Db::name($this->table)->where(['username' => $data['username']])->count() > 0) {
                $this->error("账号{$data['username']}已经存在，请使用其它账号！");
            }
        } else {
            $data['authorize'] = explode(',', isset($data['authorize']) ? $data['authorize'] : '');
            $this->authorizes = Db::name('SystemAuth')
                ->where(['status' => '1'])
                ->where('agent_id', 0)
                ->order('sort desc,id desc')
                ->select();
            if (Arr::get($data, 'id')) {
                $provinceName = Db::name('area')->where('area_id', $data['provinces_id'])->value('area_name') ?: '';
                $cityName = Db::name('area')->where('area_id', $data['city_id'])->value('area_name') ?: '';
                $countyName = Db::name('area')->where('area_id', $data['county_id'])->value('area_name') ?: '';
                $data['provinceName'] = $provinceName;
                $data['cityName'] = $cityName;
                $data['countyName'] = $countyName;
            }

        }
    }

    /**
     * 禁用代理商
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function forbid()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止操作！');
        }
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '0']);
    }

    /**
     * 启用代理商
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function resume()
    {
        $this->applyCsrfToken();
        $this->_save($this->table, ['status' => '1']);
    }

    /**
     * 删除代理商
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function remove()
    {
        if (in_array('10000', explode(',', $this->request->post('id')))) {
            $this->error('系统超级账号禁止删除！');
        }
        $this->applyCsrfToken();
        $this->_delete($this->table);
    }

     /**
     * 兼职发布配置
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function bean()
    {
        if ($this->request->isPost()) {
            $data=$this->request->post();
            if($data['id']==0){
                $data['created_at']=time();
                $data['updated_at']=time();
                $result=DB::name('Bean')->insert($data);
                if($result){
                    $this->success('添加配置成功');
                }else{
                    $this->error('添加配置失败');
                }
            }else{
                $data['updated_at']=time();
                $result=DB::name('Bean')->update($data);
                if($result){
                    $this->success('修改配置成功');
                }else{
                    $this->error('修改配置失败');
                }
            }
        } else {
            $aid = $this->request->param('id', 0);
            $result=DB::name('Bean')->where('aid',$aid)->find();
            if(empty($result)){
                $this->assign('id',0);
            }else{
                $this->assign('result',$result);
                $this->assign('id',$result['id']);            
            }
            $this->assign("aid",$aid);
            $this->fetch();
        }
    }


    /**
     * 二手发布配置
     * @auth true
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */

    public function marketPublishConfig()

    {
        if ($this->request->isPost()) {
            $data=$this->request->post();
            if($data['id']==0){
                $data['created_at']=time();
                $data['updated_at']=time();


                $res=DB::name('Bean')->insert($data);

                if($res){
                    $this->success('添加配置成功');
                }else{
                    $this->error('添加配置失败');
                }
            }else{
                $data['updated_at']=time();

                $res=DB::name('Bean')->update($data);

                if($res){
                    $this->success('修改配置成功');
                }else{
                    $this->error('修改配置失败');
                }
            }
        } else {
            $aid = $this->request->param('id', 0);
            $result=DB::name('Bean')->where('aid',$aid)->find();

            if(empty($result)){
                $this->assign('id',0);
            }else{
                $this->assign('result',$result);

                $this->assign('id',$result['id']);

            }
            $this->assign("aid",$aid);
            $this->fetch();
        }
    }


}
